<template>
	<s-layout navbar="custom1" :bgStyle="{
		color:'#000000'
	}">
		<view class="navbar-box">
			<view class="status-bar" :style="{height:sheep.$platform.device.statusBarHeight + 'px'}"></view>
			<view class="navbar ss-flex justify-start align-center ss-p-l-20" :style="{height: (44) + 'px'}">
				<view class="left ss-flex justify-center align-center">
					<view class="back ss-flex align-center" @click="onClickLeft">
						<image class="back-icon"
							src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/static/playlet/play-back.png">
						</image>
						<view>返回</view>
					</view>
					<view class="line"></view>
					<view class="num ss-flex align-center" @click="open">
						<image class="num-icon"
							src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/static/playlet/play-num.png">
						</image>
						<view>剧集</view>
					</view>
				</view>
			</view>
		</view>
		<swiper class="swiper"
			:style="{height:`calc(100vh - ${sheep.$platform.device.statusBarHeight + 44}px)`,top:`${(sheep.$platform.device.statusBarHeight + 44)}px`}"
			:vertical="state.vertical" :duration="state.duration" :current="state.current" @change="swiperChange"
			:disable-touch="true" @transition="transition">
			<template v-for="(item,index) in state.totalUrlList" :key="index">
				<swiper-item>
					<view class="video-box ss-flex-row ss-row-center ss-col-center">
						<video v-if="index === state.current" class="playVideo" :id="`vplayer${index}`"
							:src="index === state.current ? state.url : ''" :show-center-play-btn="false"
							:controls="false" :show-loading="false" :enable-progress-gesture="state.enable"
							:loop="state.loop" :autoplay="state.autoplay" @ended="ended" @click="handleVideo">
						</video>
						<image v-if="!state.play && !state.de_lock" @click.stop="handleVideo"
							src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/static/playlet/vod-play.png"
							class="vodPauseImage"></image>
						<view class="lock ss-flex flex-column justify-center align-center"
							v-if="item.lock_state === 1 && state.de_lock" @click.stop="handleVideo">
							<image class="lock-icon"
								src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/static/playlet/play-lock.png">
							</image>
							<view class="lock-title">看完广告解锁本集</view>
						</view>
					</view>
				</swiper-item>
			</template>
		</swiper>
		<su-popup :show="state.show" type="bottom" :isMaskClick="true" round="32" backgroundColor="#15141F"
			@close="close">
			<choice-video :data="state.episodes" :id="state.id" :sub_title="state.subTitle" :types="state.types"
				:index="state.index" :indexTwo="state.index2" @onItemsClick="onItemsClick"></choice-video>
		</su-popup>
	</s-layout>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import choiceVideo from './components/choice-video.vue';

	let videoAd = null

	const state = reactive({
		vertical: true,
		duration: 300,
		current: 0,
		autoplay: true,
		loop: false,
		id: '',
		totalUrlList: [],
		url: '',
		play: true,
		show: false,
		de_lock: false,
		episodes: [],
		index: 0,
		index2: 0,
		types: '',
		playNum: 0,
		subTitle: '',
		enable:true
	})

	const instance = getCurrentInstance().proxy
	const eventChannel = instance.getOpenerEventChannel();

	onLoad((e) => {
		if (e.id) {
			state.id = e.id
			state.subTitle = e.subTitle
		}

		if (e.sort) {
			state.current = Number(e.sort) - 1
		}
		loadVideoAd()
		getUrls()
		getAll()
	})

	const ended = () => {
		state.play = false
	}

	const transition = () => {
		if (state.current === state.totalUrlList.length - 1) {
			uni.showToast({
				title: '合集已完结',
				icon: 'none',
				duration: 2000
			});
		}
		state.play = true
	}
	
	const onItemsClick = async (e) => {
		state.current = e - 1
		state.de_lock = false
		state.show = false
		state.url = ''
		await getVideo()
		state.types = ''
		if (state.totalUrlList[state.current].lock_state === 1) {
			state.autoplay = false
			state.play = false
			state.enable = false
			videoPause()
			if (videoAd) {
				videoAd.show().catch(() => {
					// 失败重试
					videoAd.load()
						.then(() => videoAd.show())
						.catch(err => {
							console.error('激励视频 广告显示失败', err)
						})
				})
			}
		} else {
			state.autoplay = true
			state.play = true
			state.enable = true
			videoPlay()
		}
	}

	const open = () => {
		state.index = findGroupIndexBySort(state.episodes, state.current + 1)
		state.index2 = state.episodes[state.index].data.findIndex(item => item.sort === state.current + 1)
		state.types = 'play'
		state.show = true
	}

	const close = () => {
		state.show = false
		state.types = ''
	}

	const getAll = async () => {
		const {
			error,
			data
		} = await sheep.$api.playlet.detail({
			id: state.id
		});
		if (error == 0) {
			state.episodes = data
		}
	}

	const findGroupIndexBySort = (list, sort) => {
		return list.findIndex(group => {
			const [start, end] = group.episode_title.split('-').map(Number);
			return sort >= start && sort <= end;
		});
	};

	function onClickLeft() {
		if (sheep.$router.hasHistory()) {
			sheep.$router.back();
		} else {
			if (firstPage === 'pages/store/shop') {
				sheep.$router.go('/pages/store/index');
			} else {
				sheep.$router.go('/pages/index/home');
			}
		}
	}

	const handleVideo = () => {
		if (state.play) {
			videoPause()
		} else {
			if (state.totalUrlList[state.current].lock_state === 1) {
				if (videoAd) {
					videoAd.show().catch(() => {
						// 失败重试
						videoAd.load()
							.then(() => videoAd.show())
							.catch(err => {
								console.error('激励视频 广告显示失败', err)
							})
					})
				}
			} else {
				videoPlay()
			}
		}
	}

	const getVideoCtx = (index = 0) => {
		return uni.createVideoContext(`vplayer${index === 0 ? state.current : index}`, this)
	};

	const videoPause = (index) => {
		const video = getVideoCtx(index)
		if (!video) return
		video.pause()
		state.play = false
	}

	const videoPlay = () => {
		const video = getVideoCtx()
		if (!video) return
		video.play()
		state.play = true
	}

	const swiperChange = async (e) => {
		const {
			current
		} = e.detail;
		state.current = current
		state.de_lock = false
		state.url = ''
		state.autoplay = false
		state.play = false
		await getVideo()
		if (state.totalUrlList[state.current].lock_state === 1) {
			state.enable = false
			setTimeout(() => {
				if (videoAd) {
					videoAd.show().catch(() => {
						// 失败重试
						videoAd.load()
							.then(() => videoAd.show())
							.catch(err => {
								console.error('激励视频 广告显示失败', err)
							})
					})
				}
			}, 200)
		} else {
			state.enable = true
			state.autoplay = true
			state.play = true
			videoPlay()
		}
	}

	const getUrls = async () => {
		const {
			error,
			data
		} = await sheep.$api.playlet.playletDetailSecond({
			id: state.id
		})
		if (error == 0) {
			let de_list = []
			if (sheep.$store('playlet').isPlay(state.id)) {
				de_list = sheep.$store('playlet').getDePlay(state.id)
			}
			state.totalUrlList = data.map(item => {
				if (de_list.includes(item.sort)) {
					item.lock_state = 2
				}
				return item
			})
			getVideo()
			if (state.totalUrlList[state.current].lock_state === 1) {
				state.autoplay = false
				state.play = false
				state.enable = false
				if (videoAd) {
					videoAd.show().catch(() => {
						// 失败重试
						videoAd.load()
							.then(() => videoAd.show())
							.catch(err => {
								console.error('激励视频 广告显示失败', err)
							})
					})
				}
			} else {
				state.enable = true
			}
		}
	}

	const getVideo = async () => {
		uni.showLoading({
			title: '加载中'
		});
		const {
			error,
			data
		} = await sheep.$api.playlet.getPlayLink({
			link: state.totalUrlList[state.current].link,
			signUri: state.totalUrlList[state.current].signUri
		})
		uni.hideLoading();
		if (error === 0) {
			state.url = data
			state.playNum++
			let index = findGroupIndexBySort(state.episodes, state.current + 1)
			let index2 = state.episodes[index].data.findIndex(item => item.sort === state.current + 1)
			eventChannel.emit('changePlayNum', {
				num: state.playNum,
				index: index,
				index2: index2
			});
		}
	}



	const loadVideoAd = () => {
		if (wx.createRewardedVideoAd) {
			videoAd = wx.createRewardedVideoAd({
				adUnitId: 'adunit-902822e5614acc45'
			})
			videoAd.onLoad(() => {})
			videoAd.onError((err) => {
				console.error('激励视频光告加载失败', err)
			})
			videoAd.onClose(async (res) => {
				if (res.isEnded) {
					if (sheep.$store('playlet').isPlay(state.id)) {
						sheep.$store('playlet').updatePlay(state.id, state.totalUrlList[state.current]
							.sort)
					} else {
						sheep.$store('playlet').setPlay(state.id, [state.totalUrlList[state.current].sort])
					}
					state.totalUrlList[state.current].lock_state = 2
					state.autoplay = true
					state.play = true
					// videoPlay()
				} else {
					state.de_lock = true
				}
			})
		}
	}
</script>

<style scoped lang="scss">
	view {
		box-sizing: border-box;
	}

	.navbar-box {
		width: 100%;
		position: fixed;
		left: 0;
		z-index: 99;
	}

	.navbar {
		width: 100%;

		.status-bar {
			width: 100%;
		}

		.left {
			width: 256rpx;
			height: 58rpx;
			border-radius: 100rpx;
			background: rgba(255, 255, 255, 0.21);
			filter: blur(0rpx);
			box-shadow: inset 2rpx 2rpx 5rpx 0rpx rgba(255, 255, 255, 0.3);

			.back {
				font-size: 30rpx;
				font-weight: normal;
				color: #FFFFFF;

				.back-icon {
					width: 11.48rpx;
					height: 23.52rpx;
					margin-right: 8rpx;
				}
			}

			.line {
				width: 36rpx;
				height: 2rpx;
				transform: rotate(90deg);
				background-color: #FFFFFF;
				margin: 0;
			}

			.num {
				font-size: 30rpx;
				font-weight: normal;
				color: #FFFFFF;

				.num-icon {
					width: 36rpx;
					height: 36rpx;
					margin-right: 5rpx;
				}
			}
		}
	}

	.swiper {
		position: relative;
		width: 100vw;
		left: 0;



		.video-box {
			width: 100%;
			height: 100%;
			position: relative;


			.playVideo {
				width: 100%;
				height: 100%;
			}

			.lock {
				position: absolute;
				z-index: 999;

				.lock-icon {
					width: 58rpx;
					height: 58rpx;
				}

				.lock-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #FFFFFF;
					margin-top: 20rpx;
				}

				.lock-sub_title-icon {
					width: 32rpx;
					height: 32rpx;
				}

				.lock-sub_title {
					margin-top: 55rpx;
					font-size: 28rpx;
					font-weight: 500;
					color: #FFFFFF;
				}
			}
		}
	}

	.vodPauseImage {
		position: absolute;
		width: 134rpx;
		height: 134rpx;
		opacity: 0.35;
		animation: vodPauseName 0.1s linear forwards;
	}

	.poser-image {
		position: absolute;
		width: 100%;
		height: 100%;
	}

	@keyframes vodPauseName {
		0% {
			transform: scale(2);
			opacity: 0;
		}

		100% {
			transform: scale(1);
			opacity: 0.35;
		}
	}
</style>